import urllib2
import urllib

from urllib2 import Request

def make_url(url,get={}):

    get=urllib.urlencode(get)

    if get :
        url = url +'?' +get

    return url

def make_request(url,get={},post={}):

    return urllib2.Request(make_url(url,get),data=urllib.urlencode(post))

import copy

class Response(object):

    def __init__(self,data):

        if hasattr(data,'readlines'):
            file_=data

            self.url=file_.geturl()

            self.body=''.join(file_.readlines())

            self.headers=dict(file_.headers)
            self.info=dict(file_.info())

            self.status=file_.code
        else :
            for name in ['headers','url','body','info','status']:
                setattr(self,name,getattr(data,name,None))


import re
_pattern = re.compile('^(?P<protocol>\w+://)(?P<main>.*)')

import urlparse

class Query(dict):
    def __init__(self,qs,One=True):
        dict.__init__(self)
        if '?' in qs:
            qs=qs.split('?',1)[-1]

        self.update(dict([(key,value[0]) for (key,value) in urlparse.parse_qs(qs).iteritems()]))

class Url(object):

    def __init__(self,url):

        result= _pattern.match(url)
        if result :
            res = result.groupdict()
            self.protocol=res['protocol']

            url = res['main']

        else :
            self.protocol='http://'

        self._url=self.protocol+url

        self.url=url

        self.domain,self.path=url.split('/',1)
        self.path='/'+self.path

        self.subdomain=self.domain.split('.',1)[0]

        self.path,get_data=self.path.split('?') if '?' in self.path else (self.path,'')
        self._cleanUrl=self.domain+self.path

        self._qs=get_data

        self.get_data=Query(get_data)

def get_url(url):

    if not isinstance(url,Url):

        if isinstance(url,urllib2.Request):
            url = url.get_full_url()
        url = Url(url)

    return url

def url_join(domain,uri):

    if domain[-1] == uri[0] =='/' :
        uri=uri[1:]

    if domain[-1]!='/' and uri[0]!='/' :
        uri='/'+uri

    return domain+uri
